import React, { useState, useEffect } from 'react';
import {
  Container,
  Typography,
  Box,
  Paper,
  TextField,
  Button,
  Alert,
  CircularProgress,
  Card,
  CardContent,
  Grid,
  FormControl,
  InputLabel,
  Select,
  MenuItem,
  TableContainer,
  Table,
  TableHead,
  TableBody,
  TableRow,
  TableCell
} from '@mui/material';

function Lend({ user }) {
  const [amount, setAmount] = useState('');
  const [duration, setDuration] = useState(30);
  const [verificationCode, setVerificationCode] = useState('');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const [success, setSuccess] = useState('');
  const [userData, setUserData] = useState(null);
  const [interestRate, setInterestRate] = useState(0);
  const [creditProof, setCreditProof] = useState(null);
  const [allLends, setAllLends] = useState([]);

  useEffect(() => {
    const fetchData = async () => {
      try {
        // Fetch user data
        const userResponse = await fetch(`http://localhost:3001/api/user/${user.id}`);
        const userData = await userResponse.json();
        if (userData.success) {
          setUserData(userData.user);
          // Calculate interest rate based on credit score
          if (userData.user.creditScore >= 800) {
            setInterestRate(4); // 4% APR for high credit score
          } else if (userData.user.creditScore >= 700) {
            setInterestRate(6); // 6% APR for medium credit score
          } else {
            setInterestRate(8); // 8% APR for low credit score
          }
        }

        // Fetch all lending records
        const lendsResponse = await fetch('http://localhost:3001/api/all-lends');
        const lendsData = await lendsResponse.json();
        if (lendsData.success) {
          setAllLends(lendsData.lends);
        }
      } catch (err) {
        console.error('Error fetching data:', err);
        setError('获取数据失败');
      }
    };

    const fetchLatestCreditProof = async () => {
      try {
        const response = await fetch(`http://localhost:3001/api/credit-proofs/${user.id}/latest`);
        const data = await response.json();
        if (data.success) {
          setCreditProof(data.proof);
        }
      } catch (err) {
        console.error('Failed to fetch credit proof:', err);
      }
    };

    if (user) {
      fetchData();
      fetchLatestCreditProof();
    }
  }, [user]);

  const handleLend = async () => {
    try {
      setLoading(true);
      setError('');
      setSuccess('');

      // First verify the credit proof
      const verifyResponse = await fetch('http://localhost:3001/api/verify-credit-proof', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          proof: {
            id: creditProof.id
          },
          verificationCode: verificationCode
        }),
      });

      const verifyData = await verifyResponse.json();

      if (!verifyData.success) {
        setError('信用证明验证失败：' + verifyData.message);
        setLoading(false);
        return;
      }

      // If verification successful, proceed with lending
      const response = await fetch('http://localhost:3001/api/lend', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          userId: user.id,
          amount: parseInt(amount),
          duration: parseInt(duration),
          interestRate: interestRate
        }),
      });

      const data = await response.json();

      if (data.success) {
        setSuccess(`放贷成功！利率：${interestRate}% APR`);
        setAmount('');
        setVerificationCode('');
      } else {
        setError(data.message || '放贷失败');
      }
    } catch (err) {
      setError('操作失败，请重试');
    } finally {
      setLoading(false);
    }
  };

  const calculateInterest = () => {
    if (!amount || !duration) return 0;
    const principal = parseFloat(amount);
    const years = duration / 365;
    return (principal * interestRate * years) / 100;
  };

  return (
    <Container maxWidth="md">
      <Box sx={{ mt: 4 }}>
        <Typography variant="h4" component="h1" gutterBottom>
          放贷
        </Typography>

        <Grid container spacing={3}>
          <Grid item xs={12}>
            <Card>
              <CardContent>
                <Typography variant="h6" gutterBottom>
                  账户信息
                </Typography>
                <Typography>当前余额: {(userData?.balance || 0).toFixed(2)} 元</Typography>
                <Typography>信用评分: {userData?.creditScore || 0}</Typography>
                <Typography color="primary">
                  适用利率: {interestRate}% APR
                </Typography>
              </CardContent>
            </Card>
          </Grid>

          <Grid item xs={12}>
            <Paper sx={{ p: 3 }}>
              <Typography variant="h6" gutterBottom>
                放贷申请
              </Typography>

              {error && <Alert severity="error" sx={{ mb: 2 }}>{error}</Alert>}
              {success && <Alert severity="success" sx={{ mb: 2 }}>{success}</Alert>}

              {!creditProof && (
                <Alert severity="warning" sx={{ mb: 2 }}>
                  请先在"信用证明"页面生成信用证明
                </Alert>
              )}

              <TextField
                fullWidth
                label="信用证明验证码"
                value={verificationCode}
                onChange={(e) => setVerificationCode(e.target.value)}
                margin="normal"
                required
              />

              <TextField
                fullWidth
                label="放贷金额"
                type="number"
                value={amount}
                onChange={(e) => setAmount(e.target.value)}
                margin="normal"
                required
              />

              <FormControl fullWidth margin="normal">
                <InputLabel>贷款期限</InputLabel>
                <Select
                  value={duration}
                  onChange={(e) => setDuration(e.target.value)}
                  label="贷款期限"
                >
                  <MenuItem value={1}>1天</MenuItem>
                  <MenuItem value={30}>30天</MenuItem>
                  <MenuItem value={60}>60天</MenuItem>
                  <MenuItem value={90}>90天</MenuItem>
                  <MenuItem value={180}>180天</MenuItem>
                  <MenuItem value={365}>365天</MenuItem>
                </Select>
              </FormControl>

              {amount && duration && (
                <Box sx={{ mt: 2, p: 2, bgcolor: 'background.paper', borderRadius: 1 }}>
                  <Typography variant="subtitle1" gutterBottom>
                    预计收益
                  </Typography>
                  <Typography>
                    本金: {amount} 元
                  </Typography>
                  <Typography>
                    利息: {calculateInterest().toFixed(2)} 元
                  </Typography>
                  <Typography>
                    到期总额: {(parseFloat(amount) + calculateInterest()).toFixed(2)} 元
                  </Typography>
                </Box>
              )}

              <Button
                variant="contained"
                onClick={handleLend}
                disabled={loading || !amount || !verificationCode}
                sx={{ mt: 2 }}
              >
                {loading ? <CircularProgress size={24} /> : '确认放贷'}
              </Button>
            </Paper>
          </Grid>

          <Grid item xs={12}>
            <Paper sx={{ p: 3 }}>
              <Typography variant="h5" gutterBottom>
                放贷记录
              </Typography>
              <TableContainer>
                <Table>
                  <TableHead>
                    <TableRow>
                      <TableCell>时间</TableCell>
                      <TableCell>本金</TableCell>
                      <TableCell>利率</TableCell>
                      <TableCell>到期总额</TableCell>
                      <TableCell>到期时间</TableCell>
                      <TableCell>状态</TableCell>
                      <TableCell>放贷人</TableCell>
                    </TableRow>
                  </TableHead>
                  <TableBody>
                    {allLends.map((lend) => (
                      <TableRow key={lend.id}>
                        <TableCell>
                          {new Date(lend.timestamp).toLocaleString()}
                        </TableCell>
                        <TableCell>{lend.amount.toFixed(2)} 元</TableCell>
                        <TableCell>{lend.interestRate}%</TableCell>
                        <TableCell>{lend.totalAmount.toFixed(2)} 元</TableCell>
                        <TableCell>
                          {new Date(lend.dueDate).toLocaleString()}
                        </TableCell>
                        <TableCell>
                          {lend.status === 'pending' ? '进行中' : '已完成'}
                        </TableCell>
                        <TableCell>{lend.username}</TableCell>
                      </TableRow>
                    ))}
                    {allLends.length === 0 && (
                      <TableRow>
                        <TableCell colSpan={7} align="center">
                          暂无放贷记录
                        </TableCell>
                      </TableRow>
                    )}
                  </TableBody>
                </Table>
              </TableContainer>
            </Paper>
          </Grid>
        </Grid>
      </Box>
    </Container>
  );
}

export default Lend; 